import moment from 'moment';
import React, { useEffect, useMemo, useState } from 'react';
import { formatDuration } from '../../../../utils/time';
/**
 * 倒计时文本组件
*/
export const DownTime = (props) => {
    const { time, renderBeforeTime, renderOverTime } = props;
    const resolveTime = useMemo(() => moment(time), [time]);
    const [diffTimeStr, setDiffTimeStr] = useState('');
    function exec() {
        const now = moment();
        let res = '';
        if (resolveTime.isBefore(now)) {
            const duration = moment.duration(now.diff(resolveTime));
            const durationStr = formatDuration(duration);
            res = durationStr ? renderOverTime(durationStr) : '';
        }
        else if (resolveTime.isAfter(now)) {
            const duration = moment.duration(resolveTime.diff(now));
            const durationStr = formatDuration(duration);
            res = durationStr ? renderBeforeTime(durationStr) : '';
        }
        else {
            res = '';
        }
        setDiffTimeStr(res);
        startDownTime();
    }
    function startDownTime() {
        setTimeout(() => {
            exec();
        }, 5000);
    }
    useEffect(() => {
        if (time) {
            exec();
            startDownTime();
        }
    }, [time]);
    if (!time) {
        return <></>;
    }
    return diffTimeStr;
};
export default DownTime;
